<template>
    <div class="main">
      <p  class="main_text">基本信息管理</p>
        <!-- ############################################## 查询 ############################################## -->
        <div class="top mb20 p20">
            <el-form :model="searchData">
                <div class="df fww">
                    <el-form-item label="公司名称：" style="width: 20%;" v-if="company == 0">
                        <el-select v-model="searchData.companyNode" placeholder="公司名称" filterable class="mr20">
                            <el-option v-for="item in companyList" :key="item.id" :label="item.companyName"
                                :value="item.node" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="仓库名称：" style="width: 20%;">
                        <el-input v-model="searchData.warehouseName" placeholder="仓库名称" class="mr20" />
                    </el-form-item>
                    <el-form-item label="地址：" style="width: 20%;">
                        <el-input v-model="searchData.address" placeholder="地址" class="mr20" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchBtn">查询</el-button>
                        <el-button type="primary" plain @click="resetSearchBtn">重置</el-button>
                    </el-form-item>
                </div>
            </el-form>

        </div>
        <!-- ############################################## 表单 ############################################## -->
        <div class="content p20 cyr-flex">
            <div class="mb20">
                <el-button type="primary" @click="RucenterDialogVisible = true" v-if='roleList.write'>添加仓库</el-button>
            </div>
          <div class="cyr-flex-box" >
            <el-table @selection-change="handleSelectionChange" :data="tableData" style="width: 100%"
                 :header-cell-style="{ 'background': '#f0f6fe' }" :show-overflow-tooltip="true" v-adaptive
                border>
                <el-table-column type="selection" width="50" />
                <el-table-column label="仓库编码" width="90" prop="warehouseId" />
                <el-table-column label="仓库名称" prop="warehouseName" />
                <el-table-column label="仓库地址" prop="address" />
                <el-table-column label="创建时间" width="160" prop="createdAt" />
                <el-table-column label="更新时间" width="160" prop="updatedAt" />
                <el-table-column label="所属公司名称" prop="company_name" />
                <el-table-column label="仓库状态" prop="status">
                    <template #default="props">
                        <el-button size="small" v-if="props.row.status == 1" link type="success">启用</el-button>
                        <el-button size="small" v-else link type="warning">停用</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="160" :show-overflow-tooltip="false">
                    <template #default="props" v-if="roleList.write">
                        <el-button size="small" link type="primary" @click="editForm(props.row)">编辑</el-button>
                        <el-button size="small" link type="success" v-if="props.row.status == 0"
                            @click="startForm(props.row)">启用</el-button>
                        <el-button size="small" link type="warning" v-else @click="stopForm(props.row)">停用</el-button>
                        <el-popconfirm title="请确认仓库是否还有商品！！" @confirm="delForm(props.row.warehouseId)">
                            <template #reference>
                                <el-button v-if="company == 0" link type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
                @change="handleCurrentChange" />
          </div>
        </div>
        <el-dialog v-model="RucenterDialogVisible" width="30%" align-center>
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">添加仓库</p>
                </div>
            </template>
            <el-form ref="ruleFormRef" :rules="rules" :model="AddData" label-width="8.125rem">
                <el-form-item label="仓库名称：" prop="warehouseName">
                    <el-input v-model="AddData.warehouseName" placeholder="仓库名称：" style="width: 80%;" />
                </el-form-item>
                <el-form-item label="仓库地址：" prop="address">
                    <el-cascader placeholder="选择住址" v-model="AddData.address" :value="options" :options="options"
                        filterable style="width: 80%;" />
                </el-form-item>
                <el-form-item label="详细地址：" prop="Detailaddress">
                    <el-input v-model="AddData.Detailaddress" placeholder="详细地址：" style="width: 80%;" />
                </el-form-item>
                <el-form-item label="仓库状态：" prop="status">
                    <el-select v-model="AddData.status" placeholder="启用停用" style="width: 80%;">
                        <!-- 0 表示停用    1 表示启用 -->
                        <el-option label="启用" value="1" />
                        <el-option label="停用" value="0" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="RucenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addForm(ruleFormRef)">
                        添加
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- ****************************** 编辑仓库 ****************************** -->
        <el-dialog v-model="EditcenterDialogVisible" width="30%" align-center @close="closeDalog">
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">编辑仓库</p>
                </div>
            </template>
            <el-form :model="EditData" label-width="8.125rem">
                <el-form-item label="仓库名称：">
                    <el-input v-model="EditData.warehouseName" placeholder="仓库名称：" style="width: 80%;" />
                </el-form-item>
                <el-form-item label="仓库地址：">
                    <el-input v-model="EditData.address" placeholder="仓库地址：" style="width: 80%;" />
                </el-form-item>
                <!-- <el-form-item label="仓库面积：">
                    <el-input v-model="EditData.capacity" placeholder="仓库面积：" style="width: 80%;" />
                </el-form-item> -->
                <el-form-item label="仓库状态：">
                    <el-select v-model="EditData.status" placeholder="N-启用，D-禁用" style="width: 80%;">
                        <!-- 0 表示停用    1 表示启用 -->
                        <el-option label="启用" value="1" />
                        <el-option label="停用" value="0" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="EditcenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveEditForm">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- ****************************** 停用仓库 ****************************** -->
        <el-dialog v-model="StopcenterDialogVisible" width="30%" align-center>
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">停用仓库</p>
                </div>
            </template>
            <span>是否确定停用所选仓库</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="StopcenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="stopBtn">确定 </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- ****************************** 启用仓库 ****************************** -->
        <el-dialog v-model="StartcenterDialogVisible" width="30%" align-center>
            <template #header>
                <div class="df aic">
                    <el-icon style="color: #fff;" size="20">
                        <Edit />
                    </el-icon>&nbsp;
                    <p style="color: #fff;">启用仓库</p>
                </div>
            </template>
            <span>是否确定启用所选 仓库</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="StartcenterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="startBtn">确定 </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import { RequestWarehouseGetlistlimit, RequestWarehouseSave, RequestWarehouseDel, RequestCompanyList } from "@/api/path/index.js"
import { regionData } from 'element-china-area-data'    //获取地区
import { Edit } from '@element-plus/icons-vue'
import axios from 'axios';
import useAuthorize from "@/hooks/authorize";
let roleList = useAuthorize()

let options = regionData
const company = JSON.parse(localStorage.getItem('roleInfo')!).company
/* ************* 查询 ************* */
const searchData = ref<any>({
    warehouseName: '',
    address: '',
    companyNode: ''
})
const searchBtn = () => {
    getData()
}
const resetSearchBtn = () => {
    searchData.value.warehouseName = ''
    searchData.value.address = ''
    searchData.value.companyNode = ''
    currentPage.value = 1
    getData()
}
/* ************* 获取公司列表 ************* */
const companyList = ref<any>([])
const getCompanyList = () => {
    if (JSON.parse(localStorage.getItem('roleInfo')!).company == 0) {
        RequestCompanyList().then((res: any) => {
            console.log(res.resultObj);
            companyList.value = res.resultObj
        })
    }
}
getCompanyList()
const tableData = ref<any>([])
const ruleFormRef = ref<any>()
const AddData = ref<any>({
    warehouseName: '',
    address: '',
    Detailaddress: '',
    // capacity: '',
    status: '',
})
const EditData = ref<any>({
    warehouseName: '',
    address: '',
    Detailaddress: '',
    // capacity: '',
    status: '',
})
const rules = ref<any>({
    warehouseName: [
        { required: true, message: '请输入仓库名称', trigger: 'blur' },
        // { min: 3, max: 5, message: '请确保名称在3到5位', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '请选择地址', trigger: 'blur' },
        // { min: 3, max: 5, message: '请输入3到5位', trigger: 'blur' },
    ],
    Detailaddress: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
        // { min: 3, max: 5, message: '请输入3到5位', trigger: 'blur' },
    ],
    // capacity: [
    //     { required: true, message: '请输入仓库面积', trigger: 'blur' },
    //     // { min: 3, max: 5, message: '请输入正确的url', trigger: 'blur' },
    // ],
    status: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change',
        },
    ],
})
const multipleSelection = ref<any>([])
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val
}
const RucenterDialogVisible = ref<any>(false)
const EditcenterDialogVisible = ref<any>(false)
const StopcenterDialogVisible = ref<any>(false)
const StartcenterDialogVisible = ref<any>(false)
/* 分页器 */
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    getData()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    getData()
}
/* ************* 获取列表数据 ************* */
const total = ref<any>(1)
const currentPage = ref(1)
const pageSize = ref(10)
const getData = () => {
    regionData.forEach(item => {
        item.value! = item.label
        item.children?.forEach(val => {
            val.value! = val.label
            val.children?.forEach(i => {
                i.value! = i.label
            })
        })
    })
    RequestWarehouseGetlistlimit({
        page: currentPage.value,
        rows: pageSize.value,
        address: searchData.value.address,
        warehouseName: searchData.value.warehouseName,
        companyNode: searchData.value.companyNode,
    }).then((res: any) => {
        res.resultObj.data.forEach((item: any) => {
            item.createdAt = item.createdAt.replace(/T/g, ' ').slice(0, 16)
            item.updatedAt = item.updatedAt.replace(/T/g, ' ').slice(0, 16)
        });
        tableData.value = res.resultObj.data
        total.value = res.resultObj.total
    })
}
getData()
const companyNode = JSON.parse(localStorage.getItem('roleInfo')!).company   //所属公司节点
/* ************* 添加仓库 ************* */
const addForm = async (formEl: any | undefined) => {
    if (!formEl) return
    let res = await axios({
        url: 'http://api.tianditu.gov.cn/geocoder?ds={"keyWord":"' + AddData.value.address + ',' + AddData.value.Detailaddress + '"}&tk=0a19ac381c59eb4b32f273566fd82107',
        method: 'get',
    })
    // console.log(res.data.location.lon + '/' + res.data.location.lat);//经度，纬度
    AddData.value.longitudeAndLatitude = res.data.location.lon + '/' + res.data.location.lat
    await formEl.validate((valid: any, fields: any) => {
        if (valid) {
            /* 菜单列表请求接口 */
            RequestWarehouseSave({
                warehouseName: AddData.value.warehouseName,
                address: AddData.value.address + ',' + AddData.value.Detailaddress,
                longitudeAndLatitude: AddData.value.longitudeAndLatitude,
                // capacity: AddData.value.capacity,   //number
                status: AddData.value.status,
                companyNode: companyNode,
            }).then((res: any) => {
                if (res.code == 0) {
                    ElMessage.success(res.msg)
                    getData()
                    AddData.value.warehouseName = ''
                    AddData.value.address = ''
                    // AddData.value.capacity = ''
                    AddData.value.status = ''
                    RucenterDialogVisible.value = false
                } else {
                    ElMessage.error(res.msg)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
// const addForm = () => {
//     RequestWarehouseSave({
//         warehouseName: AddData.value.warehouseName,
//         address: AddData.value.address,
//         capacity: AddData.value.capacity,   //number
//         status: AddData.value.status,
//         companyNode: companyNode,
//     }).then((res: any) => {
//         if (res.code == 0) {
//             ElMessage.success(res.msg)
//             getData()
//             AddData.value.warehouseName = ''
//             AddData.value.address = ''
//             AddData.value.capacity = ''
//             AddData.value.status = ''
//             RucenterDialogVisible.value = false
//         } else {
//             ElMessage.error(res.msg)
//         }
//     })
// }
/* ************* 编辑仓库 ************* */
const editForm = (row: any) => {
    row.status = String(row.status)
    EditData.value = row
    EditcenterDialogVisible.value = true
}
/* ************* 编辑仓库--保存 ************* */
const saveEditForm = () => {
    RequestWarehouseSave({
        warehouseId: EditData.value.warehouseId,
        warehouseName: EditData.value.warehouseName,
        address: EditData.value.address,
        // capacity: EditData.value.capacity,   //number
        status: EditData.value.status,
        companyNode: companyNode,
    }).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            EditcenterDialogVisible.value = false
        } else {
            ElMessage.error(res.msg)
        }
    })
}
/* ************* 编辑仓库--停用--保存 ************* */
const startForm = (row: any) => {
    EditData.value = row
    StartcenterDialogVisible.value = true
}
const startBtn = () => {
    RequestWarehouseSave({
        warehouseId: EditData.value.warehouseId,
        status: 1,
        companyNode: companyNode,
    }).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            StartcenterDialogVisible.value = false
        } else {
            ElMessage.error(res.msg)
        }
    })
}
/* ************* 编辑仓库--启用--保存 ************* */
const stopForm = (row: any) => {
    EditData.value = row
    StopcenterDialogVisible.value = true
}
const stopBtn = () => {
    RequestWarehouseSave({
        warehouseId: EditData.value.warehouseId,
        status: 0,
        companyNode: companyNode,
    }).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            StopcenterDialogVisible.value = false
        } else {
            ElMessage.error(res.msg)
        }
    })
}
/* ************* 删除仓库 ************* */
const delForm = (id: any) => {
    RequestWarehouseDel(id).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.msg)
            getData()
            StopcenterDialogVisible.value = false
        } else {
            ElMessage.error(res.msg)
        }
    })
}
const closeDalog = () => {
    getData()
}

</script>

<style scoped lang="scss">
.main {
    width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
    .top {
        width: 100%;
        background-color: #fff;
    }

    .content {
        width: 100%;
        background-color: #fff;
    }
}

/* 弹出框样式 */
::v-deep .el-overlay {
    .el-dialog__header {
        background-color: #116cf8;
        margin-right: 0;
    }

    .el-dialog__title {
        color: #fff;
    }

    .el-icon svg {
        color: #fff;
    }
}

::v-deep .el-form {
    .el-icon svg {
        color: #dcdfe6;
    }
}
</style>
